#include "script.h"
#include <QDebug>
#include <QScriptEngineAgent>

Script *Script::getInstance()
{
    static Script s;
    return &s;
}

Script::Script()
{
    engine_ = new QScriptEngine;
    agent_ = engine_->agent();
}

Script::~Script()
{
    delete engine_;
    engine_ = NULL;
}

QScriptValue Script::runCode(const QString &program, Script::ContextType contextType)
{
    switch (contextType) {
    case NewContext:
    case InitialContext:
    case TemporaryContext:
        engine_->pushContext();
        break;
    case CurrentContext:
        break;
    default:
        qDebug() << Q_FUNC_INFO << QString("Unknow ContextType:%1").arg(contextType);
        return QScriptValue();
    }
    QScriptValue val = engine_->evaluate(program);
    if(contextType==InitialContext||contextType==TemporaryContext)
        engine_->popContext();

    return val;
}

void Script::pushContext()
{
    engine_->pushContext();
}

void Script::popContext()
{
    engine_->popContext();
}
